package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器
 */
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //log.info("[》》》过滤器--doFilter]:-------------------------");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 放行应该直接放行的资源
        String requestPath =  request.getRequestURI();  //当前请求路径
        String[] pathes = {  //定义直接放行的资源路径
                "/employee/login",            //登录
                "/backend",                   //管理员-静态

                "/user/sendMsg",    //客户端发送验证码
                "/user/login",      //客户端登录
                "/front",            //客户端-静态

                "/doc.html",  //Swagger及Knife4j相关的静态资源直接放行
                "/webjars",
                "/swagger-resources",
                "/v2/api-docs"
        };

        for (String pathe : pathes) {
            if(requestPath.startsWith(pathe)){
                //直接放行
                filterChain.doFilter(request,response);
                return ;
            }
        }

        HttpSession session = request.getSession();
        //2-1. 【服务端】判断用户是否登录
        Employee employee = (Employee)session.getAttribute("employee");
        if(employee!=null){
            log.info("[》》》过滤器--拦截]:通过{}",requestPath);
            log.info("[》》》当前登录--id]:{}",employee.getId());
            BaseContext.setCurrentId(employee.getId());
            //直接放行
            filterChain.doFilter(request,response);
            return ;
        }
        //2-2. 【客户端】判断用户是否登录
        User user = (User)session.getAttribute("user");
        if(user!=null){
            log.info("[》》》过滤器--拦截]:通过{}",requestPath);
            log.info("[》》》当前登录--id]:{}",user.getId());
            BaseContext.setCurrentId(user.getId());
            //直接放行
            filterChain.doFilter(request,response);
            return ;
        }


        //3. 不放行资源的访问，告知浏览器当前用户没有资源的访问权限
        log.warn("[》》》过滤器--拦截]:不通过{}",requestPath);
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);
    }
}
